package client.view;

import client.comms.PostData;
import client.model.Genre;
import client.model.Track;
import org.w3c.dom.Document;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: sam
 * Date: 16/02/12
 * Time: 06:19
 * To change this template use File | Settings | File Templates.
 */
public class DownloadResultsPanel extends JPanel implements ActionListener {

    ArrayList trackData;    // core data, standalone from table and table model (holds Track objects)
    Vector columns;
    DefaultTableModel tableModel;   // populated with tableModelData

    DownloadControlPanel downloadControlPanel;
    JTable jTable;
    JScrollPane tracksScrollPane;
    JProgressBar progressBar;

    JButton downloadButton;
    JButton cancelButton;


    Vector chosenTracks;

    public DownloadResultsPanel() {
    }

    public void init(final DownloadControlPanel downloadControlPanel) {

        this.downloadControlPanel = downloadControlPanel;

        //setLayout( new GridLayout( 2, 1 ) );
            //setLayout(new FlowLayout(FlowLayout.LEFT,0,0));

            setLayout(new BorderLayout(0,0));
            Box box = Box.createVerticalBox();

            JList list = new JList();
            list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

            // tempDataModel properties
            Vector<Vector<String>> tableModelData = new Vector<Vector<String>>();
            columns = new Vector();

            columns.add("Track");
            columns.add("Artist");

            trackData = new ArrayList();    // nList.getLength()

            tableModel = new DefaultTableModel(tableModelData, columns);

            jTable = new JTable(tableModel) {
                public boolean isCellEditable(int rowIndex, int colIndex) {
                    return false; //Disallow the editing of any cell
                }
            };

            tracksScrollPane = new JScrollPane(jTable);

            downloadButton = new JButton("Download");
            cancelButton = new JButton("Cancel");

            try {
                URL resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"save_icon.png");
                Icon tmpIcon = new ImageIcon(resourceURL);
                downloadButton.setIcon(tmpIcon);

                resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"remove_icon.png");
                tmpIcon = new ImageIcon(resourceURL);
                cancelButton.setIcon(tmpIcon);
            } catch (Exception e) {
                ReportsPanel.log("Error: "+e);
            }

            downloadButton.setPreferredSize(new Dimension((int) tracksScrollPane.getPreferredSize().getWidth(), (int) downloadButton.getPreferredSize().getHeight()));
            cancelButton.setPreferredSize(new Dimension((int) tracksScrollPane.getPreferredSize().getWidth(), (int) downloadButton.getPreferredSize().getHeight()));

            JPanel tableContainer = new JPanel();

            box.add(tracksScrollPane);


            progressBar = new JProgressBar(0, 100);
            progressBar.setValue(0);
            progressBar.setStringPainted(true);
            progressBar.setString("%");
            progressBar.setPreferredSize(new Dimension((int) tracksScrollPane.getPreferredSize().getWidth(), (int) progressBar.getPreferredSize().getHeight()));

            JPanel progressPanel = new JPanel();
            progressPanel.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
            progressPanel.add(progressBar);
            box.add(progressPanel);


            JPanel btnPanel = new JPanel();
            btnPanel.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
            btnPanel.add(downloadButton);
            cancelButton.setVisible(false);
            btnPanel.add(cancelButton);
            box.add(btnPanel);

            //tableContainer.add(box);
            add(box);

            downloadButton.addActionListener(this);
            //cancelButton.addActionListener(this);

        chosenTracks = new Vector();

            jTable.addMouseListener(new MouseListener() {
                public void mouseClicked(MouseEvent mouseEvent) {

                    int[] selectedRows = jTable.getSelectedRows();

                    downloadControlPanel.outputTextArea.setText("");

                    StringBuffer strHTMLBuffer = new StringBuffer();
                    strHTMLBuffer.append("<html><font size=2 face='Courier New' >");

                    for(int j = 0; j < selectedRows.length; j++) {
                        int chosenIndex = selectedRows[j];

                        //String tmpChosenTrack = (String) jTable.getModel().getValueAt(chosenIndex, 0);
                        //String tmpChosenArtist = (String) jTable.getModel().getValueAt(chosenIndex, 1);

                        Track track = (Track) trackData.get(chosenIndex);

                        chosenTracks.add(chosenIndex);

                        strHTMLBuffer.append("<b>Track:&nbsp;&nbsp;</b>"+track.getName() + "<br>");
                        strHTMLBuffer.append("<b>By:&nbsp;&nbsp;</b>"+track.getArtist() + "<br>");
                        strHTMLBuffer.append("<b>Run time:&nbsp;&nbsp;</b>"+track.getRunningTime() + "<br>");
                        strHTMLBuffer.append("<b>Uploaded:&nbsp;&nbsp;</b>"+track.getUploaded() + "<br>");
                        strHTMLBuffer.append("<b>Contributor:&nbsp;&nbsp;</b>"+track.getContributor() + "<br>");
                        strHTMLBuffer.append("<b>File:&nbsp;&nbsp;</b>"+track.getType() + "<br><br>");

                    }

                    downloadControlPanel.outputTextArea.setText(strHTMLBuffer.toString());

                    strHTMLBuffer.append("</font></html>");
                }

                public void mousePressed(MouseEvent mouseEvent) {}
                public void mouseReleased(MouseEvent mouseEvent) {}
                public void mouseEntered(MouseEvent mouseEvent) {}
                public void mouseExited(MouseEvent mouseEvent) {}
            });
    }

    public void actionPerformed(ActionEvent actionEvent) {

        String strAction = actionEvent.getActionCommand();

        if(strAction.equals("Download")) {
            doDownload();

        }else if(strAction.equals("Cancel")) {
            doCancel();
        }
    }

    private void doCancel() {

    }

    private void doDownload() {

        StringBuilder strReq = new StringBuilder();

        ReportsPanel.log("DownloadResutsPanel.doDownload()");

        strReq.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"+"\n");
        strReq.append("<MFRequest>"+"\n");
        strReq.append("<Request type='Download' data=''/>"+"\n");

        for (int i = 0; i < chosenTracks.size(); i++) {

            int chosenIndex = (Integer) chosenTracks.get(i);
            Track track = (Track) trackData.get(chosenIndex);

            //String tmpChosenTrack = (String) chosenTracks.get(i);
            //String trackName = tmpChosenTrack.split("/")[0];
            //String artistName = tmpChosenTrack.split("/")[1];

            ReportsPanel.log("name='"+track.getName()+"' artist='"+track.getArtist()+"'");

            strReq.append("<Track name='"+track.getName()+"' artist='"+track.getArtist()+"' />"+"\n");
        }

        strReq.append("</MFRequest>"+"\n");

        if(chosenTracks.size() > 0) {

            downloadButton.setVisible(false);
            cancelButton.setVisible(true);
            //cancelButton.setEnabled(false);
            ReportsPanel.log(strReq.toString());
            PostData postData = new PostData();
            postData.sendDataForStreamReponse(strReq.toString(), this);
        } else {
            JOptionPane.showMessageDialog(this,"Select songs for download.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void setProgressBarStr(String str) {
        progressBar.setString(str);
    }

    public void downloadComplete() {
        ReportsPanel.log("downloadComplete");
        progressBar.setString("Complete");
        cancelButton.setVisible(false);
        downloadButton.setVisible(true);
    }

    public void openDownloads(File outFile) {

            ReportsPanel.log("DownloadResultsPanel.openDownloads()");

            // http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/
            // On the Solaris Operating System and the Linux platform,
            // Before more Desktop API is used, first check this API is dependent on Gnome libraries. (false If those libraries are unavailable).
            // whether the API is supported by this particular  virtual machine (VM) on this particular host.

                String os = System.getProperty("os.name");

                boolean isWindows = os.contains("win");
                boolean isLinux = os.contains("nux") || os.contains("nix");
                boolean isMac = os.contains("mac");

                ReportsPanel.log("User Operating System "+os);

                // Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: Desktop API is not supported on the current platform
                if (Desktop.isDesktopSupported() && SettingsPanel.USER_SETTING_AUTO_OPEN.equals("yes")) {

                    // Java Desktop API can open any file/folder.
                    // but was called "outFile", not sure why, but Runtime instance appears to work
                    // fine too, so using this.
                    // keeping isDesktopSupported check, as check for Windows
                    // explorer.exe is only Windows - but isDesktopSupported could be true on Linux

                    Desktop desktop = Desktop.getDesktop();

                    try {
                        // use SettingsPanel.USER_SETTING_DOWNLOAD_DIR instead ?
                        ReportsPanel.log("outFile "+outFile);

                        ReportsPanel.log("USER_SETTING_AUTO_OPEN "+SettingsPanel.USER_SETTING_AUTO_OPEN);

                        if(os.startsWith("Windows")) {
                            Runtime.getRuntime().exec("explorer.exe "+SettingsPanel.USER_SETTING_DOWNLOAD_DIR);  // C:\\\\eclipse 3.0\\\\dev
                        } else {
                            // Not even sure this works, but need OS check, see above comment
                            //Runtime.getRuntime().exec(SettingsPanel.USER_SETTING_DOWNLOAD_DIR);

                            //Runtime.getRuntime().exec(new String[]{"/usr/bin/open",outFile.getAbsolutePath()});

                            desktop.open(outFile);
                        }

                        //Runtime.getRuntime().exec(SettingsPanel.USER_SETTING_DOWNLOAD_DIR);
                        //Runtime.getRuntime().exec("/usr/bin/open /Users/andrew");

                        //desktop.open(outFile);

                        //desktop.open(new File(SettingsPanel.USER_SETTING_AUTO_OPEN));

                    } catch (IOException e) {
                        ReportsPanel.log(e.toString());
                    }
                }
        }

    public void updateProgressBar(int progress) {
        progressBar.setValue(progress);
    }

    public void updateTracks(ArrayList newTrackData) {

        Vector<Vector<String>> newTableModelData = new Vector<Vector<String>>(); // can be retrieved from table, so always tmp in scope

        trackData.clear();

        for (int i = 0; i < newTrackData.size(); i++) {
            Vector <String> subData = new Vector<String>();

            Track track = (Track) newTrackData.get(i);

            subData.add(track.getName());
            subData.add(track.getArtist());
            //subData.add(track.getContributor());
            //subData.add(track.getRunningTime());
            //subData.add(track.getType());
            //subData.add(track.getUploaded());

            newTableModelData.add(subData);  // important that we add data Vector at same index as genreData ArrayList

            trackData.add(track);
        }

        tableModel.setDataVector(newTableModelData, columns);

        jTable.setModel(tableModel);
    }
}
